package com.hnx.admin.system.servce.impl;

import cn.hutool.core.util.ObjectUtil;
import com.hnx.admin.api.captcha.CaptchaAPI;
import com.hnx.admin.api.config.ConfigAPI;
import com.hnx.admin.api.security.api.CaptchaVerify;
import com.hnx.admin.api.security.core.SecurityPropertyAPI;
import com.hnx.admin.common.exception.CaptchaErrorException;
import com.hnx.admin.common.redis.core.RedisCore;
import com.hnx.admin.common.security.core.SecurityProperties;
import com.hnx.admin.common.security.exception.CaptchaBlankException;
import com.hnx.admin.common.security.utils.SecurityVerifyUtil;
import com.hnx.admin.system.core.SysConfigProperties;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

/*
创建人： 倔强的头发
创建时间：2024/7/12
功能描述:

*/
@Service
@RequiredArgsConstructor
public class CaptchaVerifyImpl implements CaptchaVerify, SecurityPropertyAPI, ConfigAPI, CaptchaAPI {
    private final RedisCore redisCore;
    private final SysConfigProperties sysConfigProperties;
    private final SecurityProperties securityProperties;
    @Override
    public void verify(Map<String, Object> map) {
        Boolean enableState = isCaptchaEnabled();
        if(enableState){
            validateCaptcha(map);
        }
    }

    private void validateCaptcha(Map<String, Object> data) {
        SecurityVerifyUtil.isTrue(ObjectUtil.isNotEmpty(data.get(securityProperties.getCaptcha())) && data.get(securityProperties.getCaptcha()).toString().trim().length()>0,LOGIN_CAPTCHA_NONE);
        String uuid = (String) data.get(securityProperties.getUuid());
        String verifyKey = CAPTCHA_CODE_KEY + Optional.ofNullable(uuid).orElse("");
        String codeInRedis = redisCore.getCache(verifyKey);
        if (StringUtils.isEmpty(codeInRedis)) {
            throw new CaptchaBlankException(CAPTCHA_EXPIRER);
        }
        redisCore.deleteObject(verifyKey);
        Object captchaCodeObj = data.get(securityProperties.getCaptcha());
        String captchaCode = captchaCodeObj != null ? captchaCodeObj.toString() : "";

        if (!codeInRedis.equalsIgnoreCase(captchaCode)) {
            throw new CaptchaErrorException(CAPTCHA_BAD);
        }
    }
    private Boolean isCaptchaEnabled() {
        String cacheKey = getCacheKey(sysConfigProperties.getCaptchaEnabled());
        String captchaEnabledStr = redisCore.getCache(cacheKey);
        return StringUtils.isNotBlank(captchaEnabledStr) && Boolean.parseBoolean(captchaEnabledStr);
    }
}
